import path from 'path';
import { defineConfig } from "vite";
import svgr from "vite-plugin-svgr";
import react from "@vitejs/plugin-react";
import autoprefixer from "autoprefixer";
import { fileURLToPath, URL } from "node:url";
import dts from 'vite-plugin-dts';
import { createHtmlPlugin } from "vite-plugin-html";
import { loadDependencies } from './helper';

export default defineConfig((info) => {
  const { command } = info;
  return {
    build: {
      lib: {
        entry: path.resolve(__dirname, 'src/components/AiChatRobot/index.tsx'),
        name: 'ai-chat',
        fileName: 'index',
        formats: ['es', 'cjs'],
      },
      rollupOptions: {
        //排除不相关的依赖
        external: [...Object.keys(loadDependencies())],
      },
      outDir: 'dist'
    },
    css: {
      postcss: {
        plugins: [
          autoprefixer(["Last 5 versions"])
        ],
      },
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
        }
      }
    },
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url))
      },
    },
    plugins: (() => {
      const plugins = [
        react(),
        svgr(),
      ];
      switch(command) {
        case 'serve': {
          plugins.push(createHtmlPlugin());
          break;
        }
        case 'build': {
          plugins.push(dts({ rollupTypes: true }));
          break;
        }
      }
      return plugins;
    })(),
  };
});
